// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// S [author] rhyme_lph
// l [email]  rhymelph@gmail.com
// i [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/page/dashboard/contact/detail/contact_detail_person_view.dart';
import 'package:finance_app/src/page/dashboard/contact/detail/contact_detail_transaction_view.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/widgets/button/balance_choose_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_svg_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/common_tab_bar.dart';
import 'package:flutter/material.dart' hide NestedScrollView;
import 'package:finance_app/src/provider/dashboard/contact/business_contact_detail_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:tuple/tuple.dart';
import 'package:finance_app/generated/l10n.dart';

import 'business_contacts_page.dart';

@RouterMeta(paramName: "businessContactDetailPage")
class BusinessContactDetailPage extends StatefulWidget {
  final BusinessContactEntity data;

  const BusinessContactDetailPage({Key key, this.data}) : super(key: key);

  @override
  _BusinessContactDetailPageState createState() =>
      _BusinessContactDetailPageState();
}

class _BusinessContactDetailPageState extends State<BusinessContactDetailPage>
    with
        PagePresenter<BusinessContactDetailPage, BusinessContactDetailProvider>,
        TickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    provider.contact = widget.data;
    provider.id = widget.data.id;
    _tabController = TabController(vsync: this, length: 2)
      ..addListener(() => provider.onHandleTabIndex(_tabController.index));
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
          titleWidget: listBuilder<String>(
            selector: (_, __) => __.contact?.name,
            builder: (BuildContext context, String value, Widget child) =>
                Text(value),
          ),
          actions: [
            NormalMorePopupButton(
              onSelect: provider.onSelectMenu,
              menuList: provider.menuList,
            )
          ]);

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Stack(
          children: [
            _buildRecordList(),
            _buildBottomButton(),
          ],
        ),
      );

  Widget _buildTabBar() => CommonTabBar(
        controller: _tabController,
        tabs: provider.tabList
            .map((e) => MyTab(
                  text: '$e',
                ))
            .toList(),
      );

  _buildRecordList() => Builder(
        builder: (BuildContext context) => NestedScrollView(
          controller: provider.controller,
          headerSliverBuilder: _buildSliverHeader,
          pinnedHeaderSliverHeightBuilder: () => 48.0,
          innerScrollPositionKeyBuilder: () {
            return Key("Tab${_tabController.index}");
          },
          body: Column(
            children: [
              Expanded(
                  child: TabBarView(
                      controller: _tabController, children: _buildTabView())),
            ],
          ),
        ),
      );

  List<Widget> _buildSliverHeader(
      BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SliverToBoxAdapter(
        child: _buildBalance(),
      ),
      SliverToBoxAdapter(
        child: _buildTabBar(),
      ),
    ];
  }

  Widget _buildBalance() => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            SizedBox(
              height: getDp(20),
            ),
            listBuilder<Tuple2<String, String>>(
              selector: (_, __) => Tuple2(
                  CashUtils.formatCashAmount(provider.contact?.receivingAmount),
                  CashUtils.formatCashAmount(
                      provider.contact?.unpaidInvoiceOverdueAmount)),
              builder: (BuildContext context, Tuple2<String, String> value,
                      Widget child) =>
                  BalanceChooseButton(
                title: S.current.unpaid_invoice,
                number: value.item1 ?? '0.00',
                overdueNumber: value.item2 == '0.00' ? null : value.item2,
                onTap: provider.onNavUnPaidInvoice,
                numberColor: aceGreenColor,
                borderColor: aceGreenColor.withOpacity(0.28),
              ),
            ),
            AppSpaces.h15,
            listBuilder<Tuple2<String, String>>(
              selector: (_, __) => Tuple2(
                  CashUtils.formatCashAmount(provider.contact?.payingAmount),
                  CashUtils.formatCashAmount(
                      provider.contact?.unpaidBillOverdueAmount)),
              builder: (BuildContext context, Tuple2<String, String> value,
                      Widget child) =>
                  BalanceChooseButton(
                title: S.current.unpaid_bill,
                number: value.item1 ?? '0.00',
                overdueNumber: value.item2 == '0.00' ? null : value.item2,
                onTap: provider.onNavUnPaidBill,
                numberColor: aceRedColor,
                borderColor: aceRedColor.withOpacity(0.28),
              ),
            ),
            listBuilder<Tuple2<String, String>>(
              selector: (_, __) => Tuple2(
                  CashUtils.formatCashAmount(
                      provider.contact?.totalUnpaidCredit),
                  CashUtils.formatCashAmount(
                      provider.contact?.totalUnpaidDebit)),
              builder: (BuildContext context, Tuple2<String, String> value,
                      Widget child) =>
                  Column(
                children: [
                  AppSpaces.h15,
                  BalanceChooseButton(
                    onTap: provider.onNavCreditDebit,
                    title: S.current.credit_available_debit_available,
                    number:
                        "${value.item1 ?? '0.00'} / ${value.item2 ?? '0.00'}",
                    // onTap: (){},
                    borderColor: aceBlackColor.withOpacity(0.28),
                  ),
                ],
              ),
            ),
            AppSpaces.h20,
          ],
        ),
      );

  _buildBottomButton() => listBuilder<bool>(
        selector: (_, __) => __.buttonBarIsUp,
        builder: (BuildContext context, bool value, Widget child) =>
            AnimatedPositioned(
          duration: Duration(milliseconds: 300),
          left: 0.0,
          right: 0.0,
          bottom: value
              ? MediaQuery.of(context).padding.bottom + getDp(40)
              : -getDp(60),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              NormalFloatSvgButton(
                onTap: provider.onNavAdd,
                asset: A.assetsImagesDashboardAdd,
              ),
            ],
          ),
        ),
      );

  _buildTabView() {
    return [
      NestedScrollViewInnerScrollPositionKeyWidget(
          Key("Tab0"), ContactDetailTransactionView()),
      NestedScrollViewInnerScrollPositionKeyWidget(
          Key("Tab1"), ContactDetailPersonView()),
    ];
  }
}
